/* component */
import BaseUserLabel from '@src/component/common/BaseUserLabel'
/* enum */
import { BaseSelectUserComponentNameEnum } from '@src/component/common/BaseSelectUser/model'
/* images */
import { getOssUrl } from '@src/util/assets'
const DefaultHead = getOssUrl('avatar.png')
/* hooks */
import {
  useBaseSelectUserOptions,
  useSelectUserChecked,
  useSelectUserCheckedItemList
} from '@src/component/common/BaseSelectUser/hooks'
import {
  useBaseSelectUserStoreCurrentTabType,
  useBaseSelectUserStoreIsFilterVisible,
  useBaseSelectUserStoreSearchKeyword
} from '@src/component/common/BaseSelectUser/store'
/* model */
import { SelectUserComponentUser } from '@src/component/common/BaseSelectUser/model'
/* scss */
import '@src/component/common/BaseSelectUser/components/User/item.scss'
/* vue */
// @ts-ignore
import { ComponentInstance, ComponentRenderProxy, computed, defineComponent, PropType } from 'vue'
import { CommonComponentInstance } from '@model/VC'
import { CreateElement } from 'vue'
/* util */
import { getIsOpenData } from '@src/util/platform'
import { dispatch } from '@src/util/emitter'
import { isFalse, isFalsy, isNotArray, isUndefined } from '@src/util/type'
import { alert as FeAlert } from '@src/util/platform'
import { strConcat as concat } from 'pub-bbx-utils'
import { t } from '@src/locales'

import { getCheckedItemId } from '@src/component/common/BaseSelectUser/util'

export type UserItemProps = {
  isSearch: boolean;
  isMulti: boolean;
  value: SelectUserComponentUser;
}

export interface UserItemSetupState {
  head: string | any;
}

export enum UserItemEmitEventNameEnum {
  Input = 'input'
}

export type UserItemInstance = ComponentInstance & UserItemSetupState
export type UserItemVM = ComponentRenderProxy<UserItemProps> & CommonComponentInstance & UserItemInstance

export default defineComponent({
  name: BaseSelectUserComponentNameEnum.BaseSelectUserUserItem,
  emits: [
    UserItemEmitEventNameEnum.Input
  ],
  props: {
    isSearch: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    /* 是否为多选状态 */
    isMulti: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    value: {
      type: Object as PropType<SelectUserComponentUser>,
      default: () => ({}),
      required: true
    }
  },
  setup(props: UserItemProps, { emit }) {
    
    const { addCheckedItem, removeCheckedItem, checkedItemListIdMap } = useSelectUserCheckedItemList()
    const { isChecked, isDisabled, selectLimitMessage } = useSelectUserChecked(props)
    
    const { keyword, isKeywordEmpty } = useBaseSelectUserStoreSearchKeyword()
    const { isNeedEmail } = useBaseSelectUserOptions()
    
    const { isFilterVisible } = useBaseSelectUserStoreIsFilterVisible()
    
    const isOpenData = computed(() => getIsOpenData())
    
    const isShowDelete = computed(() => {
      return props.isSearch && props.value.isDelete == 1
    })
    
    const isNotSearch = computed(() => isFalse(props.isSearch))

    const { isServiceProviderTab } = useBaseSelectUserStoreCurrentTabType()

    /* 头像 */
    const head = computed(() => {
      return props.value.head || DefaultHead
    })
    
    /* 人员标签列表 */
    const labelList = computed(() => {
      return props.value.labelNameList || []
    })
    
    /* 过滤后需要显示的人员标签列表 */
    const filterLabelList = computed(() => {
      
      const maxShowLabelCount = 2
      const maxShowLabelTextCount = 4
      
      let showLabels = labelList.value.slice(0, maxShowLabelCount).map(label => {
        return {
          text: label,
          tooltip: ''
        }
      })
      
      const beyondLabelNum = labelList.value.length - maxShowLabelCount
      
      showLabels = showLabels.filter(label => label.text).map(label => {
        
        const isLimit = label.text.length > maxShowLabelTextCount
        
        return {
          text: isLimit ? label.text.slice(0, maxShowLabelTextCount) + '...' : label.text,
          tooltip: isLimit ? label.text : ''
        }
      })
      
      if (beyondLabelNum > 0) {
        showLabels.push({
          text: `+${beyondLabelNum}`,
          tooltip: labelList.value.slice(maxShowLabelCount).join('，')
        })
      }
      
      return showLabels
    })
    
    /* 工作状态颜色样式 */
    const stateStyle = computed(() => {
      return {
        backgroundColor: props.value.stateColor
      }
    })
    
    /* 是否为 团队/部门 主管 */
    const isTeamLeader = computed(() => {
      return Boolean(props.value.isTeamLeader)
    })
    
    const checkIsDisabled = computed(() => {
      const checkedItem = checkedItemListIdMap.value[getCheckedItemId(props.value)] as SelectUserComponentUser
      return Boolean(checkedItem?.disabled)
    })
    
    const isOnlyUserDisabled = computed(() => {
      return Boolean(props.value?.disabled) || checkIsDisabled.value || false
    })
    
    return {
      head,
      keyword,
      filterLabelList,
      stateStyle,
      isChecked,
      isDisabled,
      isTeamLeader,
      isServiceProviderTab,
      isKeywordEmpty,
      isNeedEmail,
      isFilterVisible,
      isShowDelete,
      isNotSearch,
      isOpenData,
      isOnlyUserDisabled,
      checkIsDisabled,
      
      selectLimitMessage,
      addCheckedItem,
      removeCheckedItem,
    }
    
  },
  methods: {
    onUserItemClickHandler() {
      
      if (this.isFilterVisible) {
        return
      }

      if (this.checkIsDisabled) {
        return
      }
      
      if (this.isMulti) {
        return this.onUserItemMultiClickHandler()
      }
      
      // 是否选择带有邮箱的用户
      if(this.isNeedEmail && isFalsy(this.value.email)) {
        FeAlert(t('common.department.userUnbindEmail'))
        return
      }
      
      this.onUserItemSingleChoseClickHandler()
      
    },
    onUserItemSingleChoseClickHandler() {
      // 默认通过 BaseSelectUserSelectContent 组件发送 input 事件
      dispatch.call(
        this,
        BaseSelectUserComponentNameEnum.BaseSelectUserSelectContent, 
        UserItemEmitEventNameEnum.Input, 
        this.value
      )
    },
    onUserItemMultiClickHandler() {
      
      if (this.isChecked) {
        this.removeCheckedItem(this.value)
        return
      }
      
      if (this.isDisabled) {
        this.selectLimitMessage()
        return
      }
      
      // 是否选择带有邮箱的用户
      if(this.isNeedEmail && isFalsy(this.value.email)) {
        FeAlert(t('common.department.userUnbindEmail'))
        return
      }
      
      this.addCheckedItem(this.value)
      
    },
    renderHighlight(text: string) {
      
      const content = (
        <span>
          { text }
        </span>
      )
      
      // 搜索关键字为空，不需要高亮
      if (this.isKeywordEmpty) {
        return content
      }
      
      // 名称为空
      if (!text) {
        return content
      }
      
      const keywordLength = this.keyword.length
      const keywordIndex = text?.indexOf(this.keyword)
      
      if (isUndefined(keywordIndex) || keywordIndex < 0) {
        return content
      }
      
      const keywordBeforeText = text?.slice(0, keywordIndex)
      const keywordAfterText = text?.slice(keywordIndex + keywordLength)
      
      return (
        <span>
          { keywordBeforeText }
          <span class="base-select-user-user-item-highlight">
            { this.keyword }
          </span>
          { keywordAfterText }
        </span>
      )
    },
    renderUserName() {
      return this.renderHighlight(this.value.displayName)
    },
    renderPhone() {
      return this.renderHighlight(this.value.phone)
    },
    renderTagName() {
      
      if (isNotArray(this.value.tagNameList)) {
        return null
      }
      
      const tagName = concat(this.value.tagNameList as string[])
      const maxShowLength = 26
      
      if (tagName.length < maxShowLength) {
        return tagName
      }
      
      return (
        <div class="base-select-user-item__info-tag-name-content">
          <el-tooltip content={tagName} placement="top" popper-class="base-user-label-tooltip-popper">
            <span>
            { tagName }
            </span>
          </el-tooltip>
        </div>
      )
    }
  },
  render(h: CreateElement) {
    
    const isOpenData = getIsOpenData()
    
    return (
      <div 
        class={BaseSelectUserComponentNameEnum.BaseSelectUserUserItem}
        onClick={this.onUserItemClickHandler}
      >
        
        {/* start 人员多选 */}
        {this.isMulti && (
          <div class="base-select-user-user-item__checkbox">
            <el-checkbox
              disabled={this.isOnlyUserDisabled}
              value={this.isChecked}
              onInput={this.onUserItemClickHandler}
            >
            </el-checkbox>
          </div>
        )}
        {/* end 人员多选 */}
        
        {/* start 人员头像 */}
        <div class="base-select-user-user-item__head">
          <img src={this.head} />
        </div>
        {/* end 人员头像 */}
        
        {/* start 人员信息 */}
        <div class="base-select-user-user-item__info">
          
          <div class="base-select-user-item__info-top">
            
            {/* start 人员名称 */}
            <div class="base-select-user-item__info-name">
              {isOpenData ? (
                <open-data type="userName" openid={this.value.staffId}>
                </open-data>
              ) : (
                this.renderUserName()
              )}
            </div>
            {/* end 人员名称 */}
            
            
            {this.isShowDelete && (
              <div class="base-select-user-item__info-delete">
                [{t('common.base.deleted')}]
              </div>
            )}
            
            {/* start 手机号 */}
            {this.isSearch && (
              <div class="base-select-user-item__info-phone">
                { this.renderPhone() }
              </div>
            )}
            {/* end 手机号 */}
            
            {/* start 人员状态 */}
            {this.value.state && (
              <div class="base-select-user-item__info-state">
                <div class="base-select-user-item__info-state-around" style={this.stateStyle}>
                </div>
                <div class="base-select-user-item__info-state-text">
                  {this.value.state}
                </div>
              </div>
            )}
            {/* start 人员状态 */}
            
            {/* start 部门/团队 主管 */}
            {this.isTeamLeader && (
              <div class="base-select-user-item__info-leader">
                <div class="base-select-user-item__info-leader-text">
                  {this.isServiceProviderTab ? t('common.base.principal') : t('common.base.executiveDirector')}
                </div>
              </div>
            )}
            {/* end 部门/团队 主管 */}
            
          </div>
          
          <div class="base-select-user-item__info-bottom">
            
            {/* start 手机号 */}
            {this.isNotSearch && (
              <div class="base-select-user-item__info-phone">
                { this.renderPhone() }
              </div>
            )}
            {/* end 手机号 */}
            
            {/* start 部门名称 */}
            {this.isSearch && (
              <div class="base-select-user-item__info-tag-name">
                { this.renderTagName() }
              </div>
            )}
            {/* end 部门名称 */}
            
            {/* start 人员标签 */}
            <div class="base-select-user-item__info-label">
              {this.filterLabelList.map(label => {
                return <BaseUserLabel value={label.text} tooltip={label.tooltip} key={label.text} />
              })}
            </div>
            {/* end 人员标签 */}
            
          </div>
          
        </div>
        {/* end 人员头像 */}
        
      </div>
    )
  }
})
